package stephen.com.service.impl;

import stephen.com.dao.UserDao;
import stephen.com.dao.UserFocusDao;
import stephen.com.dao.UserInfoDao;
import stephen.com.model.User;
import stephen.com.model.UserFocus;
import stephen.com.model.UserInfo;
import stephen.com.service.UserService;

import java.util.Date;
import java.util.List;
import java.util.Map;

public class UserServiceImpl implements UserService {
	private UserDao userDao = new UserDao();

	private UserInfoDao userInfoDao = new UserInfoDao();
	private UserFocusDao userFocusDao = new UserFocusDao();

	@Override
	public User findUserByName(String username) {
		return userDao.findUserByName(username);
	}

	@Override
	public Map<String, Object> findUserBaseById(Integer userId) {
		return userDao.findUserById(userId);
	}

	@Override
	public User findUserByEmail(String email) {
		return userDao.findUserByEmail(email);
	}

	@Override
	public void addUser(String email, String username, String password) {
		User user = new User();
		user.setId(null);
		user.setEmail(email);
		user.setUsername(username);
		user.setPassword(password);
		user.setIsSecret("0");
		userDao.add(user);

		//更新注册时间
		User dbUser = userDao.findUserByName(username);
		UserInfo userInfo = new UserInfo();
		userInfo.setUserId(dbUser.getId());

		Date now = new Date();
		userInfo.setRegisterTime(now);
		userInfoDao.add(userInfo);
	}

	@Override
	public void updateLoginTime(Integer id) {
		//通过ID查到用户
		User user = userDao.get(id, User.class);
		//更新用户信息
		UserInfo userInfo = new UserInfo();
		userInfo.setUserId(user.getId());
		userInfo.setLoginTime(new Date());
		userInfoDao.update(userInfo);

	}

	@Override
	public void resetPassword(Integer userId, String password) {
		User user = new User();
		user.setId(userId);
		user.setPassword(password);
		userDao.update(user);
	}

	@Override
	public List<Map<String, Object>> findList(Integer userId, int page, String search) {
		List<Map<String, Object>> list = userDao.findList(userId, page, search);
		for (Map<String, Object> map : list) {
			if (null == map.get("realName")) {
				map.put("realName", map.get("username"));
			}
		}
		return list;
	}

	@Override
	//查询用户列表记录总数
	public long sumUsers() {
		return userDao.getSumUsers();
	}



	//取消关注：根据ufId删除关注表的数据
	@Override
	public void unFocus(Integer ufId) {
		userFocusDao.del(ufId, UserFocus.class);
	}

	//通过当前用户ID（userId）和关注的用户ID（userFocusId）查询关注表的某条数据
	@Override
	public UserFocus findOneFocusData(Integer userId, Integer userFocusId) {
		return userFocusDao.findOneFocusData(userId, userFocusId);
	}

	//添加关注：通过当前用户ID（userId）和关注的用户ID（userFocusId）将数据添加到关注表中
	@Override
	public void focus(Integer userId, Integer userFocusId) {
		UserFocus focus = new UserFocus();
		focus.setId(null);
		focus.setUserId(userId);
		focus.setUserFocusId(userFocusId);
		userFocusDao.add(focus);
	}
}
